package com.bird.main;

import com.bird.util.Constant;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class GameFrame extends Frame {
    private Clip bgClip;
    //实例化
    private Bird bird;
    private GameBackGround gameBackGround;
    private GameFrontGround gameFrontGround;
    private GameBarrierLayer gameBarrierLayer;

    //图片,解决屏幕闪烁,提供画笔
    private BufferedImage bufferedImage = new BufferedImage(Constant.FRAM.getWidth(), Constant.FRAM.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);

    public GameFrame() throws HeadlessException {
        setVisible(true);
        setSize(Constant.FRAM.getWidth(), Constant.FRAM.getHeight());
        setTitle(Constant.FRAM.getTitle());
        setLocation(Constant.FRAM.getX(), Constant.FRAM.getY());
        //窗口大小不可改变
        setResizable(false);
        //窗口关闭
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);//正常结束程序
            }
        });

        initGame();
        restartMusic();
        new run().start();

        //添加按键监听，重写按键和抬键的方法.
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                anjian(e);
            }

            @Override
            public void keyReleased(KeyEvent e) {
                taijian(e);
            }
        });
    }

    public void initGame() {
        //初始化对象
        bird = new Bird();
        gameBackGround = new GameBackGround();
        gameFrontGround = new GameFrontGround();
        gameBarrierLayer = new GameBarrierLayer();
    }

    @Override
    public void update(Graphics g) {
        /*解决闪烁：
         * 为了解决画面闪烁的问题，您可以使用双缓冲技术。
         * 在绘制游戏画面时，首先将内容绘制在一个离屏的缓冲区（如bufferedImage），
         * 然后再将整个缓冲区一次性绘制到屏幕上，以避免闪烁。
         * 您可以在update方法中添加双缓冲的逻辑来解决画面闪烁的问题。*/

        if (bird.life) {
            //得到图片画笔
            Graphics graphics = bufferedImage.getGraphics();
            gameBackGround.draw(graphics);
            bird.draw(graphics);
            gameFrontGround.draw(graphics);
            gameBarrierLayer.draw(graphics, bird);

            //    一次性的将图片绘制到屏幕上
            g.drawImage(bufferedImage, 0, 0, null);
        } else {
            stopMusic();
            //new Color 自设颜色
            Font font = new Font("微软雅黑", Font.BOLD, 60);
            g.setFont(font);
            
            // 计算居中位置
            FontMetrics fm = g.getFontMetrics();
            int frameWidth = Constant.FRAM.getWidth();
            int frameHeight = Constant.FRAM.getHeight();
            String text1 = "GAME OVER";
            String text2 = "空格重开";

            
    
            // 绘制主文字
            g.setColor(new Color(0xFF3D00));
            g.drawString(text1, (frameWidth - fm.stringWidth(text1))/2, frameHeight/2 - 50);
            g.drawString(text2, (frameWidth - fm.stringWidth(text2))/2, frameHeight/2 + 50);
        }
    }

    //按键
    public void anjian(KeyEvent e) {
        //获取你所按下的键
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                bird.fly(1);
                break;
            case KeyEvent.VK_SPACE:
                if (!bird.life) {
                    restart();
                }
        }

    }

    public void stopMusic() {
        if (bgClip != null && bgClip.isRunning()) {
            bgClip.stop();
            bgClip.close();
        }
    }

    public void restartMusic() {
        //在这边重新播放之前加入暂停音乐就可以了
        stopMusic();
        try {
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(new File(Constant.BK_MUSIC_PATH));
            bgClip = AudioSystem.getClip();
            bgClip.open(audioIn);
            bgClip.loop(Clip.LOOP_CONTINUOUSLY);
            bgClip.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void restart() {
        gameBarrierLayer.reStart();
        bird.reStart(this);
    }

    //抬键
    public void taijian(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                bird.fly(5);
                break;
        }
    }

    class run extends Thread {
        @Override
        public void run() {
            while (true) {
                repaint();
                try {
                    Thread.sleep(33);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
